<template>
  <div class="checkcode">
    <el-input type="text"
              v-model="checkCode"></el-input>
    <!-- 验证码 -->
    <div class="coderight"
         @click="refreshCode">
      <SIdentify :identifyCode="identifyCode"></SIdentify>
    </div>
    <div class="cant_see"><span class="not_clear">看不清</span><span class="change_pic"
            @click="refreshCode">换一张?</span></div>
  </div>
</template>

<script>
import SIdentify from '@/components/identify'

export default {
  name: 'checkcode',
  components: {
    SIdentify
  },
  mounted() {
    // 验证码初始化
    this.identifyCode = ''
    this.makeCode(this.identifyCodes, 4)
  },
  data() {
    return {
      identifyCode: '', // 自动生成的验证码
      identifyCodes: 'abcdefghijklnmopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890', // 验证码字符选择池
      checkCode: '' // 输入的验证码
    }
  },
  methods: {
    // 验证码是否正确
    isCodeCorrect() {
      // 字母转化为小写并判断
      if (this.identifyCode.toLowerCase() === this.checkCode.toLowerCase()) {
        console.log('验证码正确')
        return true
      }
      console.log('验证码错误')
      this.$message.error('验证码错误')
      // 刷新验证码
      this.refreshCode()
      return false
    },
    // 生成验证码
    makeCode(o, l) {
      for (let i = 0; i < l; i++) {
        this.identifyCode += o[this.randomNum(0, o.length)]
      }
      console.log('验证码答案', this.identifyCode) // 验证码答案
    },
    // 刷新验证码
    refreshCode() {
      this.identifyCode = ''
      this.makeCode(this.identifyCodes, 4)
    },
    // 生成随机验证码
    randomNum(min, max) {
      return Math.floor(Math.random() * (max - min) + min)
    }
  }
}
</script>

<style lang="less" scoped>
.checkcode {
  .cant_see {
    .not_clear {
      display: inline-block;
    }
    .change_pic {
      color: #1a73e8;
      cursor: pointer;
    }
  }
}
</style>